<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片列表内容区 -->
    <el-card class="box-card">
      <!-- 头部搜索操作区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getRolesList">
            <el-button slot="append" icon="el-icon-search" @click="getRolesList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" icon="el-icon-plus" @click="addRolesVisible = true">新增角色</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="rolesList" border>
        <el-table-column type="expand" width="55">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' :'','elrow','vcenter']" v-for="(item1, i1) in scope.row.children" :key="i1">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeTagById(scope.row, item1.id)">
                  {{item1.authName}}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 !== 0 ? 'bdtop' :'','vcenter']" v-for="(item2, i2) in item1.children" :key="i2">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeTagById(scope.row, item2.id)">
                      {{item2.authName}}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="i3" closable @close="removeTagById(scope.row, item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="55"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="showEidtDialog(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="deleteRolesById(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-guide" @click="showRoleRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增dialog -->
    <el-dialog
      title="新增角色信息"
      :visible.sync="addRolesVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="addFormClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改dialog -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editRolesVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="editFormClosed"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改dialog -->
    <el-dialog
      title="分配权限"
      :visible.sync="roleRightsVisible"
      width="40%"
      :close-on-click-modal="false"
      @close="roleRightsClosed"
    >
      <!-- 树列表区域 -->
      <el-tree :data="roleRightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="checkdKeys" ref="treeRef"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleRightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 查询参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      rolesList: [],
      total: 0,
      addRolesVisible: false,
      editRolesVisible: false,
      roleRightsVisible: false,
      roleRightsList: [],
      addForm: {
        roleName: "",
        roleDesc: ""
      },
      editForm: {},
      addFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ]
      },
      editFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" }
        ]
      },
      treeProps: {
        label: 'authName',
        chlidren: 'chlidren'
      },
      checkdKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList(){
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesList = res.data;
    },
    addRoles() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        //向服务器发起请求
        const { data: res } = await this.$http.post("roles", this.addForm);
        if (res.meta.status !== 201) return this.$message.error("角色新增失败");
        this.addRolesVisible = false;
        this.getRolesList();
        this.$message.success("角色新增成功");
      });
    },
    addFormClosed() {
      this.$refs.addFormRef.resetFields();
    },
    editFormClosed() {
      this.editForm = {};
      this.$refs.editFormRef.resetFields();
    },
    async showEidtDialog(roleId) {
      const { data: res } = await this.$http.get("roles/" + roleId);
      if (res.meta.status !== 200)
        return this.$message.error("角色信息获取失败");
      this.editForm = res.data;
      this.editRolesVisible = true;
    },
    editRoles() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        //向服务器发起请求
        console.log(this.editForm);
        const { data: res } = await this.$http.put("roles/" +this.editForm.roleId, 
        {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
        });
        if (res.meta.status !== 200) return this.$message.error("角色修改失败");
        this.editRolesVisible = false;
        this.getRolesList();
        this.$message.success("角色修改成功");
      });
    },
    async deleteRolesById(id) {
      const result = await this.$confirm("确认删除此角色吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(error => error);
      if(result !== "confirm") return this.$message.info("已取消删除");
      const {data: res} = await await this.$http.delete('roles/' + id);
      if(res.meta.status !== 200) return this.$message.error("角色删除失败");
      this.$message.success("角色删除成功");
      this.getRolesList();
    },
    async removeTagById(role, rightId){
      const result = await this.$confirm("确认删除此权限吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(error => error);
      if(result !== "confirm") return this.$message.info("已取消删除");
      const {data: res} = await await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
      if(res.meta.status !== 200) return this.$message.error("权限删除失败");
      this.$message.success("权限删除成功");
      //this.getRolesList();
      role.children = res.data;
    },
    async saveRoleRights(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(',');
      const {data: res} = await await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr});
      if(res.meta.status !== 200) return this.$message.error("分配权限失败");
      this.$message.success("分配权限成功");
      this.getRolesList();
      this.roleRightsVisible = false;
    },
    roleRightsClosed(){
      this.roleRightsVisible = false;
    },
    async showRoleRightsDialog(role){
      this.checkdKeys.length = 0;
      this.roleId = role.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      this.roleRightsList = res.data;
      this.getLeafKeys(role, this.checkdKeys);
      this.roleRightsVisible = true;
    },
    getLeafKeys(node, array) {
      if(!node.children){
        return array.push(node.id);
      }
      node.children.forEach(item => this.getLeafKeys(item, array));
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag{
    margin:7px;
  }
  .bdtop{
    border-top: 1px solid #eee;
  }
  .bdbottom{
    border-bottom: 1px solid #eee;
  }
  .elrow .el-col{
    text-align: left;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>